package com.school.express.controller;

import com.alibaba.druid.filter.AutoLoad;
import com.school.express.domain.User;
import com.school.express.service.ExpressService;
import com.school.express.service.UserService;
import com.school.support.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import zhibi.common.support.exception.MessageException;
import zhibi.common.support.exception.TipException;
import zhibi.common.support.response.Response;
import zhibi.common.util.security.SecurityUtil;

/**
 * Created by 执笔 on 2017/3/18.
 */
@RequestMapping
@Controller
public class IndexController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private ExpressService expressService;

    /**
     * 登录后的首页
     *
     * @return
     */
    @RequestMapping({"", "index"})
    public String index() {
        return "index";
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(SecurityUtil.MD5(password, PASSWORD_COUNT).toLowerCase());
        user = userService.selectOne(user);
        if (null == user) {
            throw new TipException("用户名或者密码错误", "/login");
        }
        if (user.getStatus() == STAUTS_0) {
            throw new TipException("用户呗锁定", "/login");
        }
        session.setAttribute(SESSION_USER, user);
        session.setAttribute("userType", user.getType());
        return redirect("/");
    }

    @RequestMapping("logout")
    public String logout() {
        session.removeAttribute(SESSION_USER);
        return "login";
    }

    @RequestMapping("modifyPwd")
    @ResponseBody
    public Response<String> modifyPwd(String password, String pwd, String pwd2) {
        if (!pwd.equals(pwd2)) {
            throw new MessageException("两次密码不一样");
        }
        User user = sessionUser();
        user = userService.selectByPK(user.getId());
        if (!user.getPassword().equalsIgnoreCase(SecurityUtil.MD5(password, PASSWORD_COUNT))) {
            throw new MessageException("原密码不对");
        }
        user.setPassword(SecurityUtil.MD5(pwd, PASSWORD_COUNT));
        userService.updateByIdSelective(user);
        session.removeAttribute(SESSION_USER);
        return Response.ok("");

    }

    @RequestMapping("stock")
    public String stock(){
        expressService.stock();
        return "stock";
    }
}
